package controllers

import (
	"fmt"
	"strconv"

	"gitee.com/yizhongi/wfw/models"
	"gitee.com/yizhongi/wfw/util"
	"github.com/beego/beego/v2/adapter/orm"
)

type StoreApiController struct {
	BaseController
}

// @Title AddTask
// @添加一个任务
// @Param   page           query   int      false       "页数"
// @Param   limit          query   int      false        "每页数目"
// @Success 0 {object} models.DeployTask
// @router /add [post]
func (c *StoreApiController) Add() {
	o := orm.NewOrm()
	s := models.Store{}
	if err := c.ParseForm(&s); err != nil {
		fmt.Println(err)
	} else {
		CheckLogin(&s)
		o.Insert(&s)
		if err == nil {
			c.SuccessJson("保存成功", s.ID)
		}
	}
}

// @Title AddTask
// @添加一个任务
// @Param   page           query   int      false       "页数"
// @Param   limit          query   int      false        "每页数目"
// @Success 0 {object} models.DeployTask
// @router /edit [post]
func (c *StoreApiController) Edit() {
	o := orm.NewOrm()
	src := models.Store{}
	if err := c.ParseForm(&src); err != nil {
		fmt.Println(err)
	} else {
		dst := models.Store{ID: src.ID}
		o.Read(&dst)
		util.CopyStructValue(src, &dst)
		CheckLogin(&dst)
		i, err1 := o.Update(&dst)
		if err1 == nil {
			fmt.Println(i)
			c.SuccessJson("保存成功", src.ID)
		}
	}
}

// @Title getTasks
// @Description get all the tasks
// @Param   page           query   int      false       "页数"
// @Param   limit          query   int      false        "每页数目"
// @Success 0 {object} models.DeployTask
// @router /list
func (this *StoreApiController) List() {
	limit, err_1 := this.GetInt("limit")
	page, err_2 := this.GetInt("page")
	if err_1 != nil && err_2 != nil {
		this.ErrorJson(500, err_1.Error()+err_2.Error(), nil)
	}
	var stores []*models.Store

	o := orm.NewOrm()
	stose := new(models.Store)
	ss := o.QueryTable(stose)
	cnt, err := ss.Count()
	if err != nil {
		this.ErrorJson(500, err.Error(), nil)
	}
	ss.Limit(limit, (page-1)*limit)
	num, err := ss.All(&stores)
	fmt.Printf("Returned Rows Num: %v, %v", num, err)
	if err != nil {
		this.ErrorJson(500, err.Error(), nil)
	}
	this.LayuiSuccessJson(cnt, stores)
}

// @Title AddTask
// @添加一个任务
// @Param   page           query   int      false       "页数"
// @Param   limit          query   int      false        "每页数目"
// @Success 0 {object} models.DeployTask
// @router /login/?:id [get]
func (c *StoreApiController) Login() {
	sid, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
	fmt.Println(sid)
	o := orm.NewOrm()
	s := models.Store{ID: sid}
	err := o.Read(&s)
	if err == nil {
		CheckLogin(&s)
	}
	o.Update(&s)
	c.SuccessJson("", nil)
}

func CheckLogin(s *models.Store) {
	crc := util.NewContainerRuntimeAPIClient()
	s.IsValid = crc.RegistryLogin(s.UserName, s.Password, s.Addr)
}
